package top.jfunc.common.utils.local;

import top.jfunc.common.utils.MapUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * 在子线程中就可以通过{@link StringMapInfoHolderUtil}获取{@link ThreadLocal}变量
 */
public class HolderWrapperCallable<T> implements Callable<T> {

    private final Callable<T> callable;

    private final Map<String, String> map;

    public HolderWrapperCallable(Callable<T> callable) {
        this(callable, true);
    }
    public HolderWrapperCallable(Callable<T> callable, boolean readonly) {
        this.callable = callable;
        if(readonly){
            //这种不会破坏主线程的map
            Map<String, String> localMap = StringMapInfoHolderUtil.getLocalMap();
            map = new HashMap<>(localMap.size());
            map.putAll(localMap);
        }else {
            map = StringMapInfoHolderUtil.getLocalMap();
        }
    }

    @Override
    public T call() throws Exception {
        if(!MapUtil.isEmpty(this.map)){
            StringMapInfoHolderUtil.addMap2Local(this.map);
        }
        // 装饰器模式，执行run方法
        try {
            return callable.call();
        }finally {
            StringMapInfoHolderUtil.clear();
            this.map.clear();
        }
    }
    
}